/**
 * 将base64转换为文件
 * @param dataurl
 * @returns {Blob}
 */
var dataURLtoFile = function(dataurl) {
  var arr = dataurl.split(',')
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

/**
 * 图片添加水印
 * @param file
 * @param text
 * @param onload
 * @param onerror
 */
export default function watermark(file, text, onload, onerror) {
  var fontStyle = {
    fontSize: 14,
    lineHeight: 30,
    fontFamily: 'microsoft yahei',
    // fillStyle: 'rgba(255, 255, 255, 0.7)'
    fillStyle: '#409EFF'
  }
  var config = {
    initWidth: 260, // 图片在界面上展示的宽度，基准宽度
    spacing: 20 // 重复文字间的间距
  }
  if (!file) {
    onerror('不存在图片文件')
    return
  }
  var fileReader = new FileReader()
  fileReader.readAsDataURL(file)
  fileReader.onload = function() {
    var img = new Image()
    img.src = fileReader.result
    img.onload = function() {
      // 创建canvas进行绘图
      var canvas = document.createElement('canvas')
      var ctx = canvas.getContext('2d')
      if (img.width > 4000) {
        canvas.width = 4000
        canvas.height = img.height * (4000 / img.width)
      } else {
        canvas.width = img.width
        canvas.height = img.height
      }

      var ratio = canvas.width / config.initWidth
      fontStyle.fontSize = fontStyle.fontSize * ratio
      config.spacing = config.spacing * ratio

      ctx.drawImage(img, 0, 0, canvas.width, canvas.height)

      ctx.font = fontStyle.fontSize + 'px ' + fontStyle.fontFamily
      ctx.fillStyle = fontStyle.fillStyle
      console.log(fontStyle.lineHeight, canvas.height, fontStyle.fontSize)
      ctx.fillText(text, canvas.width - (fontStyle.fontSize * text.length + config.spacing), canvas.height - fontStyle.fontSize)

      // 转为base64格式
      var imgData = canvas.toDataURL(file.type)
      // 转为file对象传递出去
      var imgFile = dataURLtoFile(imgData)
      onload(imgFile)
    }
    img.onerror = function(event) { onerror({ errCode: 'WATERMARK_ERROR' }) }
  }
  fileReader.onerror = function(event) { onerror({ errCode: 'WATERMARK_ERROR' }) }
}
